import {defineConfig, loadEnv} from 'vite';
import vue from '@vitejs/plugin-vue';
import AutoImport from 'unplugin-auto-import/vite';
import Components from 'unplugin-vue-components/vite';
import Icons from 'unplugin-icons/vite';
import IconsResolver from 'unplugin-icons/resolver';
import {ElementPlusResolver} from 'unplugin-vue-components/resolvers';
import {createSvgIconsPlugin} from 'vite-plugin-svg-icons';
import VueSetupExtend from 'vite-plugin-vue-setup-extend';
import legacy from '@vitejs/plugin-legacy';
import path from 'path';

const pathSrc = path.resolve(__dirname, 'src');

// https://vitejs.dev/config/
export default defineConfig(({mode}) => {
  const env = loadEnv(mode, process.cwd());
  const {VITE_PORT, VITE_APP_BASE_API, VITE_API} = env;
  return {
    css: {
      postcss: {
        plugins: [
          {
            postcssPlugin: 'internal:charset-removal',
            AtRule: {
              charset: (atRule) => {
                if (atRule.name === 'charset') {
                  atRule.remove();
                }
              }
            }
          }
        ]
      },
      preprocessorOptions: {
        scss: {
         // additionalData: "@import '@/assets/styles/index.scss';",
          javascriptEnabled: true,
          charset: false
        }
      }
    },
    resolve: {
      alias: [
        {
          find: '@',
          replacement: pathSrc
        },
        {
          find: '@element-plus/icons/lib/dist$',
          replacement: './src/plugins/icon.js'
        }
      ]
    },
    plugins: [
      vue(),
      VueSetupExtend(),
      legacy({
        targets: ['cover 99.5%']
      }),
      AutoImport({
        imports: ['vue', 'vue-router'],
        resolvers: [
          ElementPlusResolver(),
          IconsResolver({
            prefix: 'Icon'
          })
        ],
        //dts: path.resolve(pathSrc, 'types', 'auto-import.js'),
      }),
      Components({
        resolvers: [
          ElementPlusResolver(),
          // 自动注册图标组件
          IconsResolver({
            enabledCollections: ['ep'],
          }),
        ],
       // dts: path.resolve(pathSrc, 'types', 'components.js'),
      }),
      Icons({
        autoInstall: true,
      }),
      createSvgIconsPlugin({
        iconDirs: [path.resolve(process.cwd(), 'src/assets/icons/svg')],
        symbolId: 'icon-[dir]-[name]',
        svgoOptions: {
          plugins: [
            {
              name: 'removeAttrs',
              params: {attrs: ['class', 'data-name', 'fill', 'stroke']}
            }
          ]
        }
      })
    ],
    optimizeDeps: {
      include: ['element-plus']
    },
    server: {
      host: '0.0.0.0',
      port: VITE_PORT,
      open: true,
      proxy: {
        [VITE_APP_BASE_API]: {
          target: VITE_API,
          changeOrigin: true,
          rewrite: (path) => path.replace(new RegExp(`^${VITE_APP_BASE_API}`), '')
        }
      }
    }
  }

})
